package com.ph.myblog.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalendarUtil {

	private static String DFormat = "yyyy-MM-dd HH:mm:ss";

	public static String CalendarToString(Calendar calendar) {

		String time = null;

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DFormat);

		time = simpleDateFormat.format(calendar.getTime());

		return time;
	}

	// 将Calendar转换为String
	public static String CalendarToString(Calendar calendar, String format) {

		String time = null;

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);

		time = simpleDateFormat.format(calendar.getTime());

		return time;
	}

	// 获得String的时间
	public static Calendar getCalendar(String dateString, String format) {

		Calendar calendar = null;

		if (dateString != null && dateString.length() > 0) {

			calendar = Calendar.getInstance();

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);

			Date date = null;

			try {

				date = simpleDateFormat.parse(dateString);
				calendar.setTime(date);
			} catch (ParseException e) {

				e.printStackTrace();
			}

		}

		return calendar;
	}

	// 转换String
	public static Calendar getCalendar(String dateString, int hour, int minute,
			int second) {

		Calendar calendar = null;

		if (dateString != null && dateString.length() > 0) {

			int year, month, day;

			calendar = Calendar.getInstance();
			String[] str = dateString.split("-");
			year = new Integer(str[0]);
			month = new Integer(str[1]) - 1;
			day = new Integer(str[2]);
			calendar.set(year, month, day, hour, minute, second);
		}

		return calendar;
	}

	// 获取当前日期
	public static Calendar getCurrentDate() {

		Calendar nowCalendar = Calendar.getInstance();
		nowCalendar.set(nowCalendar.get(nowCalendar.YEAR), nowCalendar
				.get(nowCalendar.MONTH), nowCalendar.get(nowCalendar.DATE),
				nowCalendar.get(nowCalendar.HOUR), nowCalendar
						.get(nowCalendar.MINUTE), nowCalendar
						.get(nowCalendar.SECOND));
		return nowCalendar;
	}
}
